import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@views/Home'
import { isLogin } from '@utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    meta: {
      needLogin: false,
      keepAlive: true
    },
    component: Home
  },
  {
    path: '/cate',
    name: '分类',
    meta: {
      needLogin: false,
      keepAlive: true
    },
    component: () => import('@views/Cate')
  },
  {
    path: '/cart',
    name: '购物车',
    meta: {
      needLogin: true
    },
    component: () => import('@views/Cart')
  },
  {
    path: '/user',
    meta: {
      needLogin: true
    },
    name: '我的',
    component: () => import('@views/User')
  },
  {
    path: '/detail/:id',
    name: '详情页',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Detail')
  },
  {
    path: '/itemLists',
    name: '商品列表',
    meta: {
      needLogin: false
    },
    component: () => import('@views/ItemLists')
  },
  {
    path: '/login',
    name: '登录',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Login')
  },
  {
    path: '/register',
    name: '注册',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Register')
  },
  {
    path: '/orderCreate',
    name: '确认订单',
    meta: {
      needLogin: true
    },
    component: () => import('@views/OrderCreate')
  },
  {
    path: '/addressLists',
    name: '所有联系人',
    meta: {
      needLogin: true
    },
    component: () => import('@views/AddressLists')
  },
  {
    path: '/addressAdd',
    name: '增加联系人',
    meta: {
      needLogin: true
    },
    component: () => import('@views/AddressAdd')
  },
  {
    path: '/addressUpdate',
    name: '修改联系人',
    meta: {
      needLogin: true
    },
    component: () => import('@views/AddressUpdate')
  },
  {
    path: '/search',
    name: '搜索页',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Search')
  },
  {
    path: '/searchResult',
    name: '搜索结果',
    meta: {
      needLogin: true
    },
    component: () => import('@views/SearchResult')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    if (isLogin()) {
      // 登录了
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    // 不需要登录访问的路由
    next()
  }
})
export default router
